package com.nl.math;

import java.math.BigDecimal;

public class Power {

	public static double power(double base ,int exponent){
		if(new BigDecimal(base).compareTo(new BigDecimal(0.0))==0 && exponent ==0){
			throw new RuntimeException(String.format("bad arguments:base %f,exponent %d",base,exponent));
		}
		if(exponent==0){
			return 1;
		}
		double result=base;
		boolean positive=(exponent>0);
		for(int i=1,len=exponent*(positive?1:-1);i<len;i++){
			result*=base;
		}
		if(!positive){
			result=1/result;
		}
		return result;
	}
	
	public static double power2(double base ,int exponent){
		if(new BigDecimal(base).compareTo(new BigDecimal(0.0))==0 && exponent ==0){
			throw new RuntimeException(String.format("bad arguments:base %f,exponent %d",base,exponent));
		}
		if(exponent==0){
			return 1;
		}
		boolean positive=(exponent>0);
		double result = powerWithUnsigned(base,positive?exponent:(-1)*exponent);
		if(!positive){
			result=1/result;
		}
		return result;
	}

	
	/**
	 * a^n=a^(n/2)*a^(n/2) n为偶数
	 * a^n=a^((n-1)/2)*a^((n-1)/2)*a n为偶数
	 * 通过递归减少乘法次数
	 * @param base
	 * @param exponent
	 * @return
	 */
	public static double powerWithUnsigned(double base,int exponent){
		if(exponent==0){
			return 1;
		}
		if(exponent==1){
			return base;
		}

		double result = powerWithUnsigned(base, exponent>>1);
		result*=result;
		if((exponent & 0x1)==1){
			result*=base;
		}

		return result;
	}
	
	public static void main(String[] args) {
		
		System.out.println(power2(2, 2));
		System.out.println(power2(2, -2));
		System.out.println(power2(2, 0));

	}
}
